import { Menu } from "antd";
import {
  MenuUnfoldOutlined,
  AppstoreAddOutlined,
  MenuFoldOutlined,
} from "@ant-design/icons";
import styles from "./root.module.css";
import { useEffect, useMemo, useState } from "react";
import NButton from "@/components/n-button/index.jsx";
import { treeMap } from "@/utils/util.js";
import { get, isEmpty, isExist, last, notExist } from "wsp-toolkit";
import { menuItems } from "@/router/main.jsx";
import { useNavigate } from "react-router-dom";
import { getAuthMenu, getUserInfo, isAdmin } from "@/utils/index";

export default function CustomerMenu() {
  const [collapsed, setCollapsed] = useState(false);
  const navigate = useNavigate();

  const defaultOpenKeys = [];
  const defaultSelectedKeys = [];
  const authMenuPathList = getAuthMenu();
  const filterMenuItems = treeMap(menuItems, (x, parent, i, level) => {
    if (isAdmin()) {
      return x;
    }
    if (notExist(x.children)) {
      return authMenuPathList.includes(x.path) ? x : null;
    }
    return isEmpty(x.children) ? null : x;
  });

  treeMap(filterMenuItems, (x) => {
    if (location.pathname === x.path) {
      defaultSelectedKeys.push(x.key);
    } else if (new RegExp(`^${x.path}/`).test(location.pathname)) {
      defaultOpenKeys.push(x.key);
    }
    return x;
  });
  function onClick({ key }) {
    const propPath = key.split("-").flatMap((x, i, xs) => {
      if (i > 0 && i < xs.length) {
        return ["children", x];
      }
      return [x];
    });
    const route = get(filterMenuItems, propPath);
    navigate(route.path);
  }

  return (
    <div className={styles.menu}>
      <div className={styles.menuContent}>
        <Menu
          mode="inline"
          items={filterMenuItems}
          style={{ border: "none" }}
          inlineCollapsed={collapsed}
          onClick={onClick}
          defaultOpenKeys={defaultOpenKeys}
          defaultSelectedKeys={defaultSelectedKeys}
        />
      </div>
      {/*<div className={styles.menuCollapsed}>
        <NButton type="text" onClick={() => setCollapsed((x) => !x)}>
          {collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
        </NButton>
      </div>*/}
    </div>
  );
}
